new Vue({
    el: '#app',
    data() {
        return {
            type: '0', // 0：查看地址 1：选择地址
            form: { // 分页查询条件
                SQLSerialNumber: 'm_member_address_info',
                PaginationNumber: 1,
                RowAmount: 10,
                Condition: utf8ToBase64(getCookie('openId')),
            },
            tableData: [],
            total: 0,//总条数
            loading: false,// 节流阀门
        }
    },
    beforeCreate() {
        function setRem() {
            const designWidth = 750; // 设计稿宽度（rpx）
            const maxWidth = 540; // 可选：限制最大宽度（如手机端常见值）
            const screenWidth = Math.min(window.innerWidth, maxWidth);
            const scale = screenWidth / designWidth;
            document.documentElement.style.fontSize = scale + 'px';
        }
        setRem();//1rem = 0.5px 对标小程序在 375px 宽的屏幕上，1rpx = 0.5px（因为 750rpx / 375px = 2）
    },
    mounted() {
        let URL = window.location.href;
        this.type = getQueryObject(URL, 'type') || '0';
        this.init();
    },
    methods: {
        async init(callback) {
            const res = await Promise.allSettled([
                this.getList(this.form),
            ]);
            callback ? callback() : null;
        },
        async getList(data) { // 分页查询
            if (this.loading) return;
            this.loading = true;//开启节流
            try {
                const res = await generalApi.generalPaginationQueryBySQLSerialNumberWithClient(data);
                this.tableData = [...this.tableData, ...res.Rows];
                this.total = res.TotalRows;
            } catch (error) {
                console.error(error);
            }
            this.loading = false;//关闭节流
        },
        handleScroll(e) { // 滚动监听
            const { scrollTop, clientHeight, scrollHeight } = e.target;
            if (scrollTop + clientHeight >= scrollHeight && !this.loading && this.tableData.length < this.total) {
                this.form.PaginationNumber++;
                this.getList(this.form)
            }
        },
        handleAdd() {// 添加地址
            if (isMiniprogram()) { // 小程序环境
                wx.miniProgram.navigateTo({
                    url: `/pages/index/submitAddress?action=Add`,
                })
            } else { // 其它环境
                this.$showToast({
                    title: '暂未开放'
                });
            }
        },
        async handleChange(item) {// 切换地址
            if (this.type == '1') { // 修改
                try {
                    const data = await generalApi.generalQueryBySQLSerialNumberWithClient({
                        SQLSerialNumber: 'm_member_address_info',
                        Condition: utf8ToBase64(getCookie('openId')),
                        ExtensionCondition: utf8ToBase64(`AND (member_address_info.isDefault='1' OR member_address_info.Address_SerialNumber='${item.Address_SerialNumber}')`)
                    })
                    if (data.length > 1) {
                        let member_address_info = [];
                        data.forEach(item => {
                            const obj = configOriginal(item);
                            obj.isDefault = (obj.isDefault == '1' ? '0' : '1');
                            member_address_info.push(obj);
                        })
                        let lJSONObject_DataSet = {
                            Modify: { member_address_info }
                        }
                        const res = await generalApi.generalSaveByRequestBodyWithClient({
                            Data: lJSONObject_DataSet
                        })
                        if(res.Status == 'success') {
                            this.$showToast({
                                title:'切换成功'
                            });
                            window.history.back();
                        } else {
                            this.$showToast({
                                title:'切换失败，请重试！'
                            });
                        }
                    } else {
                        window.history.back();
                    }
                } catch (error) {
                    console.error(error);
                }
            }
        }
    },
})
